<template>
  <div class="habit-list">
    <h2>习惯管理</h2>
    
    <!-- 添加习惯表单 -->
    <div class="habit-form">
      <h3>添加新习惯</h3>
      <form @submit.prevent="createHabit">
        <input v-model="newHabit.name" placeholder="习惯名称" required>
        <textarea v-model="newHabit.description" placeholder="习惯描述"></textarea>
        <input type="number" v-model="newHabit.suggested_duration" placeholder="建议时长(分钟)" required>
        <input type="number" v-model="newHabit.points_reward" placeholder="积分奖励" required>
        <button type="submit">添加习惯</button>
      </form>
    </div>

    <!-- 习惯列表 -->
    <div class="habits">
      <div v-for="habit in habits" :key="habit.id" class="habit-item">
        <h3>{{ habit.name }}</h3>
        <p>{{ habit.description }}</p>
        <p>建议时长: {{ habit.suggested_duration }}分钟</p>
        <p>积分奖励: {{ habit.points_reward }}</p>
        <button @click="startTimer(habit)">开始专注</button>
        <button @click="viewRecords(habit.id)">查看记录</button>
      </div>
    </div>

    <!-- 专注计时器弹窗 -->
    <div v-if="showTimer" class="timer-modal">
      <div class="timer-content">
        <h3>专注计时 - {{ currentHabit.name }}</h3>
        <div class="timer-display">{{ formatTime(timerCount) }}</div>
        <div class="timer-controls">
          <button @click="startFocus" v-if="!isTimerRunning">开始</button>
          <button @click="pauseFocus" v-if="isTimerRunning">暂停</button>
          <button @click="stopFocus">结束</button>
        </div>
        <div class="timer-mode">
          <button @click="setTimerMode('normal')" :class="{ active: timerMode === 'normal' }">正计时</button>
          <button @click="setTimerMode('pomodoro')" :class="{ active: timerMode === 'pomodoro' }">番茄钟</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HabitList',
  props: {
    childId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      habits: [],
      newHabit: {
        name: '',
        description: '',
        suggested_duration: 30,
        points_reward: 10
      },
      showTimer: false,
      currentHabit: null,
      timerCount: 0,
      timerInterval: null,
      isTimerRunning: false,
      timerMode: 'normal', // 'normal' or 'pomodoro'
      pomodoroConfig: {
        workTime: 25 * 60, // 25分钟
        breakTime: 5 * 60,  // 5分钟
        isBreak: false
      }
    }
  },
  methods: {
    async fetchHabits() {
      try {
        const token = localStorage.getItem('token')
        const response = await axios.get(`/api/habits/${this.childId}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        this.habits = response.data
      } catch (error) {
        console.error('获取习惯列表失败:', error)
      }
    },
    async createHabit() {
      try {
        const token = localStorage.getItem('token')
        const userRole = localStorage.getItem('userRole')
        
        const habitData = {
          name: this.newHabit.name,
          description: this.newHabit.description,
          suggested_duration: this.newHabit.suggested_duration,
          points_reward: this.newHabit.points_reward
        }

        // 如果是家长，需要添加child_id
        if (userRole === 'parent') {
          habitData.child_id = parseInt(this.childId)
        }

        const response = await axios.post('/api/habits', habitData, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (response.data.message) {
          alert(response.data.message)
          await this.fetchHabits()
          this.resetForm()
        }
      } catch (error) {
        console.error('创建习惯失败:', error)
        alert(error.response?.data?.error || '创建习惯失败')
      }
    },
    resetForm() {
      this.newHabit = {
        name: '',
        description: '',
        suggested_duration: 30,
        points_reward: 10
      }
    },
    startTimer(habit) {
      this.currentHabit = habit
      this.showTimer = true
      this.timerCount = 0
    },
    startFocus() {
      if (!this.isTimerRunning) {
        this.isTimerRunning = true
        this.timerInterval = setInterval(() => {
          this.timerCount++
          if (this.timerMode === 'pomodoro') {
            this.handlePomodoroTimer()
          }
        }, 1000)
      }
    },
    pauseFocus() {
      clearInterval(this.timerInterval)
      this.isTimerRunning = false
    },
    async stopFocus() {
      clearInterval(this.timerInterval)
      this.isTimerRunning = false
      
      // 记录专注时间
      try {
        await axios.post('http://localhost:5000/api/records', {
          habit_id: this.currentHabit.id,
          duration: this.timerCount,
          date: new Date().toISOString().split('T')[0],
          completed: true,
          points_earned: this.calculatePoints()
        })
        this.showTimer = false
        this.timerCount = 0
        this.currentHabit = null
      } catch (error) {
        console.error('记录专注时间失败:', error)
      }
    },
    handlePomodoroTimer() {
      const { workTime, breakTime, isBreak } = this.pomodoroConfig
      const currentCycle = isBreak ? breakTime : workTime
      
      if (this.timerCount >= currentCycle) {
        this.pomodoroConfig.isBreak = !this.pomodoroConfig.isBreak
        this.timerCount = 0
        // 提醒切换
        this.notifyPomodoroChange()
      }
    },
    notifyPomodoroChange() {
      const message = this.pomodoroConfig.isBreak ? '休息时间到！' : '专注时间到！'
      // 这里可以添加声音提醒或其他提醒方式
      alert(message)
    },
    calculatePoints() {
      // 根据专注时间计算积分
      return Math.floor(this.timerCount / 60) * this.currentHabit.points_reward
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    },
    setTimerMode(mode) {
      this.timerMode = mode
      this.timerCount = 0
      this.pomodoroConfig.isBreak = false
    },
    viewRecords(habitId) {
      this.$router.push(`/habits/${this.childId}/records/${habitId}`)
    }
  },
  async mounted() {
    await this.fetchHabits()
  },
  beforeDestroy() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval)
    }
  }
}
</script>

<style scoped>
.habit-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.habit-form {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.habit-form form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.habit-item {
  border: 1px solid #ddd;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
}

.timer-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.timer-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.timer-display {
  font-size: 48px;
  margin: 20px 0;
  font-family: monospace;
}

.timer-controls {
  margin-bottom: 20px;
}

.timer-mode button {
  margin: 0 5px;
  opacity: 0.7;
}

.timer-mode button.active {
  opacity: 1;
  border: 2px solid #42b983;
}

button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin: 5px;
}

button:hover {
  background-color: #3aa876;
}
</style> 